package com.iteye.trafficRecorder;

import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.os.Handler;

/**
 * HTTP请求包装帮助类
 * @author chen_weihua
 *
 */
public class HttpClientHelper {

    public static void asyncGetTextRequest(Context context, String url, 
    		ResponseListener callback) {
    	HttpGet get = new HttpGet(url);
    	asyncRequest(context, get, new CallbackWrapper(callback));
    }
    
    public static void asyncPostTextRequest(Context context, String url, 
    		List<NameValuePair> params, ResponseListener callback) throws Exception {
    	asyncPostTextRequest(context, url, params, callback, null);
    }
    
    public static void asyncPostTextRequestNoHandler(Context context, String url, 
    		List<NameValuePair> params, ResponseListener callback, Object tagObj) throws Exception {
    	HttpPost post = new HttpPost(url);
    	if (params != null) {
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		}
    	CallbackWrapper wrapper = new CallbackWrapper(callback);
    	wrapper.setTagObj(tagObj);
    	asyncRequestNoHandler(context, post, wrapper);
    }
    
    public static void asyncPostTextRequest(Context context, String url, 
    		List<NameValuePair> params, ResponseListener callback, Object tagObj) throws Exception {
    	HttpPost post = new HttpPost(url);
    	if (params != null) {
    		UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			post.setEntity(form);
		}
    	CallbackWrapper wrapper = new CallbackWrapper(callback);
    	wrapper.setTagObj(tagObj);
    	asyncRequest(context, post, wrapper);
    }
    
    private static void asyncRequestNoHandler(Context context, HttpUriRequest request, CallbackWrapper callback) {
    	new AsynchronousSender(context, request, callback).start();
    }
    
    private static void asyncRequest(Context context, HttpUriRequest request, CallbackWrapper callback) {
    	new AsynchronousSender(context, request, new Handler(), callback).start();
    }
    
}
